package com.googlecode.contests_repo.servlets;


import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.contests_repo.core.config.ConfigurationManager;
import com.oreilly.servlet.MultipartRequest;

/**
 * A servlet for uploading files in the repository.
 * 
 * @author deni
 */
@WebServlet("/upload_file")
public class UploadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
  
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		String repoRoot = ConfigurationManager.getInstance().getRepoRoot();

		String encodedLocation = "";
		boolean success = true;
		try {
			MultipartRequest mpRequest = new MultipartRequest(request, repoRoot, Integer.MAX_VALUE);
			
			encodedLocation = mpRequest.getParameter("location");
			String location = URLDecoder.decode(encodedLocation, "UTF-8");
			
			String absoluteLocation = repoRoot + File.separator + location;
			File file = mpRequest.getFile("file");
			success = file.renameTo(new File(absoluteLocation + File.separator + file.getName()));
			assert success;			
		} catch(IOException e) {
			e.printStackTrace();
			success = false;
		}
		
		response.sendRedirect("view_folder.jsp?path=" + encodedLocation + "&fileUploadSuccessful=" + success);
	}

}
